package com.it.sun.esaychat.chat.service.impl;

import com.it.sun.easychat.model.exception.ApplicationException;
import com.it.sun.easychat.model.vo.UserVO;
import com.it.sun.esaychat.chat.entity.MessageEntity;
import com.it.sun.esaychat.chat.service.IMessageSendServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * @author sunmannian
 * @ClassName com.it.sun.esaychat.chat.service.impl.MessageSendServices
 * @Date 2020/5/27 15:44
 * @Version V1.0
 * Description  <发送消息服务>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/27
 */
@Service
public class MessageSendServices implements IMessageSendServices {


    @Autowired
    private SimpMessagingTemplate template;


    @Override
    public void sendToUser(MessageEntity messageEntity) {
        UserVO userVO = messageEntity.getTo().stream().findFirst().orElseThrow(() ->
                new ApplicationException("", 0));
        template.convertAndSend
                ("/user/topic/" + userVO.getId(), messageEntity);
    }

    @Override
    public void chatRoom(MessageEntity messageEntity) {
        messageEntity.getTo().stream().forEach((user) ->
                template.convertAndSend
                        ("/user/queue/" + user.getId(), messageEntity)
        );
    }
}
